define(function(require, exports, module) {
	'use strict';
    
    var rk = require('rk');
    
    
    require('../su/accordion/oaTabCtrl');
    
    require('./colleagueCurtainCtrl');
    require('./colleagueContentCtrl');
    
    //引入jstree
    $.widget('rk.colleaguePanelCtrl', $.rk.oaPanelCtrl, {
        _create: function () {
            var me = this;
            var elem = me.element;
            //1，模板文件请在WEB-INFO/templates/oa中追加
            //2，请在src/resources/sub-deps/oa中引入
            //3，如下所示，调用rk.template方法生成html
            //var html = rk.template("tpl_colleague_panel", {});//在子页面的jsp或/WEB-INF/templates/中定义
            var temp = require('oa/tmpl/colleague/tpl_colleague_panel.tpl');
            var html = rk.templateText(temp,{});
            //将html显示在elem中
            elem.html(html);
            me._listeners();
        },
        _listeners: function () {
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='colleague_panel_tab_click']", function () {
                var tab = $(this);
                var forTable = tab.attr("forTable");
                if (elem.find('[tabForTable="' + forTable + '"]').hasClass("active")) {
                    return;
                }
                elem.find("[act='favorites_create_new']").hide();
                elem.find("[tabAct='colleague_depart_table']").hide();
                elem.find("[table-name='" + forTable + "']").show();
                elem.find('[act="colleague_panel_tab"]').removeClass("active");
                elem.find('[tabForTable="' + forTable + '"]').addClass("active");
                var forLoadData = tab.attr("forLoadData");
                me.loaddata(forLoadData);
            });
            elem.on('click','.oa-close-panel',function(){
                rk.oa.closePanel();
            });
            me._follow_listener();
            me._user_query_listener();
            me._row_click_listeners();

            me._favorites_create_listener();
        },
        _follow_listener:function(){
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='colleague_table_follow']", function(e){
                e.stopPropagation();
                var follow = $(this);
                follow.next().find("[act='moreColleagueOperationMenu']").hide();
                var uid = follow.attr("uid");
                var followStatus = follow.attr("follow");
                if(follow.hasClass('disable')) return;
                follow.addClass('disable');
                if(followStatus == 1){
                    rk.confirm(rk.i18n('COLLEAGUE_CONFIRM_UNFOLLOW'), function () {
                        rk.post("/json/oa_relation/delFollow.action", {fId: uid}, function (json) {
                            if (json.status == 0) {
                                follow.attr("follow", "0");
                                follow.attr("title", rk.i18n('COLLEAGUE_ADD_FOLLOW'));
                                follow.removeClass("has-attent-btn");
                                follow.addClass("attent-btn");
                                rk.noticeSuccess(rk.i18n('COLLEAGUE_OPERATE_SUCCESS'));
                                elem.find("[act='addAllFollow']").removeClass("hasattention-all");
                                elem.find("[act='addAllFollow']").attr("title",rk.i18n('COLLEAGUE_FOLLOW') + rk.i18n('COLLEAGUE_ALL_COLLEAGUE'));
                            } else {
                                rk.noticeError(rk.i18n('COLLEAGUE_SYSTEM_ERROR'));
                            }
                            follow.removeClass('disable');
                        });
                    },function(){
                        follow.removeClass('disable');
                    });
                }else if(followStatus == 0){
                    rk.post("/json/oa_relation/addFollow.action",{fId:uid},function(json){
                        if(json.status == 0) {
                            follow.attr("follow", "1");
                            follow.attr("title", rk.i18n('COLLEAGUE_CANCEL_FOLLOW'));
                            follow.removeClass("attent-btn");
                            follow.addClass("has-attent-btn");
                            rk.noticeSuccess(rk.i18n('COLLEAGUE_OPERATE_SUCCESS'));
                        }else{
                            rk.noticeError(rk.i18n('COLLEAGUE_SYSTEM_ERROR'));
                        }
                        follow.removeClass('disable');
                    });
                }
                return false;
            });
            elem.on("click", "[act='addAllFollow']", function(){
                var follow = $(this);
                var uids = follow.attr("uids");
                if(!follow.hasClass("hasattention-all")) {
                    if(follow.hasClass('disable')) return;
                    follow.addClass('disable');
                    rk.post("/json/oa_relation/addAllFollow.action", {fIds: uids}, function (json) {
                        if (json.status == 0) {
                            me.loaddata("colleague");
                            rk.noticeSuccess(rk.i18n('COLLEAGUE_OPERATE_SUCCESS'));
                        } else {
                            rk.noticeError(rk.i18n('COLLEAGUE_SYSTEM_ERROR'));
                        }
                    });
                }
            });
        },
        _user_query_listener:function(){
            var me = this;
            var elem = me.element;
            elem.on('input propertychange', "[act='user_name_text']", function(){
                var val = elem.find("[act='user_name_text']").val();
                if(val){
                    elem.find("[act='user_name_clear']").show();
                }else{
                    elem.find("[act='user_name_clear']").hide();
                }
            });
            var clean_user_name = function(){
                elem.find("[act='user_name_text']").val("");
                elem.find("[act='user_name_clear']").hide();
            };
            elem.on("click", "[act='user_name_clear']", function(){
                clean_user_name();
            });
            var nameQuery = function(){
                var colleagueName = elem.find("[act='user_name_text']").val();
                if(colleagueName) {
                    me.loaddata("colleague_query", {pageNo: 1, pageSize: 20, colleagueName:colleagueName});
                }
            };
            elem.on("click", "[act='user_name_query']", function(){
                nameQuery();
            });
            elem.on('keydown', '[act="user_name_text"]', function (e) {
                if (e.keyCode == 13) {
                    nameQuery();
                }
            });
            elem.on("click", "[act='colleague_query_return_table']", function(){
                elem.find("[act='colleague_query_operation_div']").hide();
                clean_user_name();
                me.loaddata("colleague");
            });
            elem.on('click', "[act='colleague_query_high_grade']", function(){
                me._showSearch();
            });
        },
        _row_click_listeners:function(){
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='moreColleagueOperation']", function(){
                var button = $(this);
                //button.parent().find("[act='moreColleagueOperationMenu']").toggle();
                var isFirst = button.parents('[act="colleague_user_row"]').is(':first-child');
                var isLast = button.parents('[act="colleague_user_row"]').is(':last-child');
                var menu = button.parent().find("[act='moreColleagueOperationMenu']");
                var pos = {
                                my: "right bottom+20",
                                at: "right top",
                                within: button.parents('.mCSB_container'),
                                of: button,
                                collision: "flip"
                            };
                if(isLast && !isFirst){
                    pos.my = 'right bottom-100';
                    pos.at = 'right top';
                }
                if(isLast && isFirst){//仅有一条的时候
                    button.parents('.oa-list:first').height(300)//足够空间弹出菜单
                }
                menu.toggle().position(pos);
                return false;
            });
            // elem.on("blur", "[act='moreColleagueOperation']", function(){
            //     var button = $(this);
            //     button.parent().find("[act='moreColleagueOperationMenu']").hide();
            // });
            elem.on("mouseenter", "[act='colleague_user_row']", function(e){
                $(this).find("[act='moreColleagueOperationMenu']").hide();
            });
            elem.on("click", "[act='colleague_user_row']", function(e){
                //e.stopPropagation();
                e.preventDefault();
                var row = $(this);
                var uid = row.attr("uid");
                var param = {uid:uid};
                var userStatus = row.attr("userStatus");
                if(userStatus == 1) {
                    me._showDetails(param, "middle")
                    elem.find("[act='colleague_user_row']").removeClass("show-content-hover");
                    row.addClass("show-content-hover");
                }else{
                    rk.noticeError(rk.i18n('COLLEAGUE_NOT_ACTIVATE_ACCOUNT_ERROR'));
                }
                row.find("[act='moreColleagueOperationMenu']").hide();
            });
            elem.on("click", "[act='push_private_msg']", function(e){
                e.stopPropagation();
                var button = $(this);
                var uid = button.attr("uid");
                var uname = button.attr("uname");
                if($('#privaemsg').data('msgInited') === 'privatemsginited'){
                     $('#privatemsg').privateMsgCtrl('openMsg',uid,uname);
                }else{
                    require.async(['page/js/privatemsg/privateMsgCtrl'],function(){
                        $('#privatemsg').privateMsgCtrl();
                        $('#privatemsg').privateMsgCtrl('openMsg',uid,uname);
                    });
                }
                button.closest("[act='moreColleagueOperationMenu']").hide();
            });
            elem.on("mousedown", "[act='push_task']", function(){
                var button = $(this);
                var uid = button.attr("uid");
                var uname = button.attr("uname");
                require.async(["../task/dialogs/createDialogCtrl"],function(){
                    rk.dialog({
                        title: rk.i18n('COLLEAGUE_DISTRIBUTE_TASK'),
                        width: 570,
                        success: function (dialogElem) {
                            var forSelf = false;
                            var myUserId = window.SESSION.user.id;
                            if(myUserId == uid){
                                forSelf = true;
                            }
                            dialogElem.createTaskDialogCtrl({
                                forSelf: forSelf,
                                otherUser: {
                                    id: uid,
                                    name: uname
                                },
                                onSuccess: function () {
                                    $.msg(rk.i18n('COLLEAGUE_ADD_TASK_SUCCESS'), 1);
                                    rk.closeDialog();
                                }
                            });
                        },
                        footer: [{
                            act: 'nextstep', visible: true, text: rk.i18n('COLLEAGUE_NEXT_STEP')
                        }, {
                            act: 'prevstep', color: 'white', visible: true, text: rk.i18n('COLLEAGUE_PREVIOUS_STEP')
                        }, {
                            act: 'save', visible: true, text: rk.i18n('COLLEAGUE_CONFIRM')
                        }]
                    });
                });
                button.closest("[act='moreColleagueOperationMenu']").hide();
            });
            elem.on("mousedown", "[act='push_schedule']", function(){
                var button = $(this);
                var uid = button.attr("uid");
                var uname = button.attr("uname");
                var icon = button.attr("icon");
                //alert("建日程---uid="+uid)
                require.async(["../schedule/asset/utils/scheduleUtil"],function(scheduleUtil){
                    scheduleUtil.popupEditor({
                        ownerUser:{
                            value: uid,
                            label: uname,
                            icon : icon
                        }
                    });
                });
                button.closest("[act='moreColleagueOperationMenu']").hide();
            });
        },
        _favorites_create_listener: function() {
            var me = this;
            var elem = me.element;
            elem.on("click", "[act='favorites_create_new']", function() {
                require.async(["./content/favoritesCreateNewPanelCtrl"], function() {
                    rk.dialog({
                        title: rk.i18n('ADD') + rk.i18n('OA_FAVORITES'),
                        success: function (contentElem) {
                            contentElem.favoritesCreateNewPanelCtrl();
                        },
                        close: function() {
                            me.loaddata("favorites");
                        },
                        footer: ['cancel', {
                            act: 'ok', visible: true, text: rk.i18n('SAVE')
                        }]
                    });
                });
            });
        },
        _showSearch: function(){
            var me = this;
            me.popupCurtain({
                onSuccess: function(curtain){
                    curtain.colleagueCurtainCtrl();
                }
            });
        },
        _showDetails: function(param,size){
           var me = this;
            me.popupContent({
                size:size,
                onSuccess: function(contentElem){
                    contentElem.colleagueContentCtrl(param);
                }
            });
        },
        //init方法中，用来初始化数据
        _init: function () {
            var me = this;
            var elem = me.element;
            me.loaddata("colleague");
        },
        loaddata: function (type, param) {
            var me = this;
            var elem = me.element;
            if (type === "colleague" || type==="colleague_query") {
                elem.find("[act='colleague_coll_table']").beLoading();
                elem.find('[act="colleague_page_parent"]').hide();
                if(!param){
                    param = {pageNo:1,pageSize:20};
                }
                var colleague_type_function=function(){
                    elem.find("[act='colleague_query_operation_div']").hide();
                };
                var colleague_type = {
                    colleague:function(){
                        elem.find("[act='colleague_query_operation_div']").hide();
                    },
                    colleague_query:function(json){
                        elem.find("[act='colleague_query_operation_div']").show();
                        elem.find("[act='colleague_name_query_num']").html(json.dataCount+"");
                    }
                };
                rk.post("/json/oa_colleague/colleague-query-list.action",param,function(json){
                    if(json.status === 0){
                        if(json.colleagues && json.colleagues.length>0) {
                            var dataList = json.colleagues;
                            var temp = require('oa/tmpl/colleague/tpl_colleague_colleague_table_row.tpl');
                            //var html = rk.templateText(temp,{});
                            var listHtml = "";

                            $.each(dataList, function (i, dataJson) {
                                dataJson.currentUserId = json.currentUserId;
                                listHtml += rk.templateText(temp, dataJson);
                            });
                            //act="colleague_coll_table"
                            if (json.followAll) {
                                elem.find("[act='addAllFollow']").addClass("hasattention-all");
                                elem.find("[act='addAllFollow']").attr("title", rk.i18n('COLLEAGUE_FOLLOW_ALL_COLLEAGUE'));
                            }
                            elem.find("[act='colleague_coll_table']").html(listHtml);
                            elem.find("[act='addAllFollow']").attr("uids", json.uids);
                            colleague_type[type].call(this, json);
                            //colleague_page
                            elem.find('[act="colleague_page_parent"]').show();
                            elem.find('[act="colleague_page"]').rkPaging({
                                pagenum: json.pageNo,  //（可选）当前页数，默认1
                                pagesize: json.pageSize,  //（可选）当前每页显示条数，默认20
                                rowscount: json.dataCount, //所有数据数
                                onChange: function (pagenum) {
                                    var params = param;
                                    params.pageNo = pagenum;
                                    params.pageSize = json.pageSize;
                                    me.loaddata(type, params)
                                }
                            });
                        }else{
                            require.async(["oa/tmpl/colleague/tpl_colleague_none.tpl"], function (temp) {
                                var html = rk.templateText(temp, {text: rk.i18n('COLLEAGUE_NO_SUITABLE_COLLEAGUE_ERROR')});
                                elem.find("[act='colleague_coll_table']").html(html);
                            });
                        }
                    }else{
                        rk.noticeError(rk.i18n('COLLEAGUE_SYSTEM_ERROR'));
                    }
                    elem.find('[act="beScroll"]').beScroll();
                    elem.find("[act='colleague_table_follow']").beTip({dir:"left"});
                    elem.find("[act='addAllFollow']").beTip({dir:"left"});
                    elem.find("[act='colleague_query_high_grade']").beTip({dir:"left"});
                    elem.find("[act='moreColleagueOperation']").beTip({dir:"left"});
                });
                //hasattention-all
            } else if (type === "depart_tree") {
                require.async(["./colleagueDepartPanelCtrl.js"],function(){
                    elem.find("[act='group_depart_table_tree']").colleagueDepartPanelCtrl();
                });
            } else if (type === "favorites") {
                elem.find("[act='favorites_create_new']").show();
                $(elem.find("[act='favorites_table']")).beLoading();
                require.async(["./favoritesPanelCtrl.js"], function() {
                    elem.find("[act='favorites_table']").favoritesPanelCtrl();
                });
            }
        }

    });

});










































































